package com.gjs.bedorder.control;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gjs.bedorder.business.BedInfo;
import com.gjs.bedorder.business.LastInfo;

/**
 * Servlet implementation class BedOrderInit
 */
@WebServlet("/bedorder")
public class BedOrderInit extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BedOrderInit() {
        super();
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Cache-Control","no-cache"); 
		response.setHeader("Pragma","no-cache"); 
		response.setDateHeader("Expires",0); 
		
		request.setCharacterEncoding("utf-8");
		
		HttpSession session = request.getSession();
		Integer count = (Integer) session.getAttribute("count");
		if (count != null && count < 1) {
			session.removeAttribute("msg");
			session.removeAttribute("count");
			count = null;
		}
		if (count != null && count >= 1) {
			count--;
			session.setAttribute("count", count);
		}
		
		
		String userId = request.getParameter("user_id");
		String name = request.getParameter("name");
		if (name != null && name.length() != 0)
			name = new String(name.getBytes("iso8859-1"), "UTF-8");
		
		if (userId != null && userId.length() != 0 && session.getAttribute("userId") == null 
			&& name != null && name.length() != 0 && session.getAttribute("name") == null) {
			session.setAttribute("userId", userId);
			session.setAttribute("name", name);
		}

		userId = (String) session.getAttribute("userId");
	
		List<Map<String, Object>> allBeds = BedInfo.getAllBeds();
		
		Map<String, Object> orderedBed = BedInfo.getOrderedBedInfo(allBeds, userId);
		session.setAttribute("orderedBed", orderedBed);
		
		if (orderedBed != null && count == null) {
			session.setAttribute("msg", "4");
		}
		
		request.setAttribute("allBeds", allBeds);
		request.setAttribute("remainBeds", BedInfo.getRemainBeds());
		request.setAttribute("last_infos", LastInfo.getAllLastInfos());
		
		request.getRequestDispatcher("/order.jsp").forward(request, response);
	}

}
